#include <unistd.h>
#include <cstdlib>
#include <iostream>
#include <ctime>
#include "blockqueue.hpp"
#include "task.hpp"
#include "RingQuene.hpp"
#include "Ring.hpp"

void *produce(void *bk)
{
    RingQueue<task>* block = static_cast<RingQueue<task>*>(bk);
    
    while (true)
    {
        int x1 = rand() % 10;
        usleep(10);
        int x2 = rand() % 10 + 1;
        char op = g_op[rand() % 4];
        task t(x1, x2, op);

        //生产
        printf("%p生产任务:%s\n", pthread_self(), t.gettask().c_str());
        block->push(t);
        sleep(2);
    }
}

void* consume(void* bk)
{
    RingQueue<task>* block = static_cast<RingQueue<task>*>(bk);
    while (true)
    {
        //消费
        task n;
        block->pop(&n);
        n.run();
        printf("%p完成任务:%s\n", pthread_self(), n.getresult().c_str());
        //sleep(1);
    }
}

int main()
{
    srand(time(NULL));
    RingQueue<task>* block = new RingQueue<task>();
    pthread_t ptid[3], ctid[5];
    for (int i = 0; i < 3; i++)
    {
        pthread_create(&ptid[i], nullptr, produce, block);
    }

    for (int i = 0; i < 5; i++)
    {
        pthread_create(&ctid[i], nullptr, consume, block);
    }

     for (int i = 0; i < 3; i++)
    {
        pthread_join(ptid[i], nullptr);
    }

    for (int i = 0; i < 5; i++)
    {
        pthread_join(ctid[i], nullptr);
    } 
    

    delete block;
    return 0;
}